package com.yuxin.tongyi.lsll.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.yuxin.tongyi.lsll.R;
import com.yuxin.tongyi.lsll.pojo.VersionInfo;

public class UpdateManager{

	private Context mContext;
	//提示信息
	private String updateMsg = "有最新的软件包哦，亲快下载吧~";
	//返回的安装包url
	private String apkUrl ;
	private Dialog noticeDialog;
	private Dialog downloadDialog;
	 /* 下载包安装路径 */
    private String savePath = "";  //"test/";
    private String saveFileName =  "newaplication.apk";
    private String pathName = "/install/";
    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private int progress;
    private Thread downLoadThread;
    private boolean interceptFlag = false;
    private HttpRequestUtil request;
    private boolean flag;
    private String status;
    
    private Handler mHandler = new Handler(){
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);  //下载中
				break;
			case DOWN_OVER:
				installApk();  //安装应用程序
				break;
			default:
				break;
			}
    	};
    };
    
//	public UpdateManager(Context context) {
//		this.mContext = context;
//	}
	
	//外部接口让主Activity调用
	public void checkUpdateInfo(){
		showNoticeDialog();
	}
	
	
	/**
	 * 检查更新
	 */
	private void showNoticeDialog(){
		AlertDialog.Builder builder = new Builder(mContext);
		//检测是否有版本更新
		request = new HttpRequestUtil();
		flag = request.validateVersion();
		VersionInfo info = getVersionInfo();
		if(info!=null) {
		String currVersion = getAppVersionName(mContext);
		String newVersion = info.getVersionCode();
		Log.i("当前版本： ",currVersion);
		Log.i("服务器版本： ",newVersion);
		if(newVersion!=null&&!"".equals(newVersion)) {
			if(!newVersion.equals(currVersion)) {
				apkUrl = info.getUrl();
				Log.i("服务器版本url： ", apkUrl);
				builder.setTitle("软件版本更新");
				builder.setMessage(updateMsg);
				builder.setPositiveButton("下载", new OnClickListener() {			
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						showDownloadDialog();			
					}
				});
				builder.setNegativeButton("以后再说", new OnClickListener() {			
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();				
					}
				});
				noticeDialog = builder.create();
				noticeDialog.show();
			}
		}
		}
	}
	
	/**
	 * 获取版本信息
	 * @return
	 */
	private VersionInfo getVersionInfo() {
		if(flag) {
			status = request.getStatus();
			if (status != null && !"".equals(status)) {
				List<Object> objects = request.getObjList();
				if (objects != null && objects.size() > 0) {//获取版本信息
				    Object obj = objects.get(0);
				    if(obj instanceof VersionInfo) {
				    	return (VersionInfo)obj;
				    }
				}else {
					return null;
				}
			}else {
				new AlertDialog.Builder(mContext).setTitle("错误").setMessage("数据处理异常").show();
			}
		}else {
			new AlertDialog.Builder(mContext).setTitle("访问错误").setMessage("访问服务器失败").show();
		}
		return null;
	}
	
	/**
	 * 下载显示框
	 */
	private void showDownloadDialog(){
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("软件版本更新");
		
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar)v.findViewById(R.id.progress);
		
		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {	
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();//隐藏下载框
		downloadApk();
	}
	
	/**
	 * 下载线程
	 */
	private Runnable mdownApkRunnable = new Runnable() {
		InputStream is;
		FileOutputStream fos;
		public void run() {
			try {
				URL url = new URL(apkUrl);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				is = conn.getInputStream();
				//判断sdcard是否存在
				if(FileTool.sdCardExist()) {//存在
					savePath = mContext.getExternalCacheDir().toString()+pathName;
				}else {//sdcard不存在
					savePath = mContext.getCacheDir().toString()+pathName;
				}
				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = savePath+saveFileName;
				File ApkFile = new File(apkFile);
				fos = new FileOutputStream(ApkFile);
				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.
				downloadDialog.dismiss();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (fos != null) {
						fos.close();
					}
					if (is != null) {
						is.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	};
	
	 /**
     * 下载apk
     * @param url
     */
	
	private void downloadApk(){
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}
	 /**
     * 安装apk
     * @param url
     */
	private void installApk(){
		File apkfile = new File(savePath+saveFileName);
        if (!apkfile.exists()) {
            return;
        }    
        
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); 
        mContext.startActivity(i);
	}
	
	
	/**
	 * 返回当前应用程序版本名
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager manage = context.getPackageManager();
			PackageInfo info = manage.getPackageInfo(context.getPackageName(), 0);
			versionName = info.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			Log.e("VersionInfo", "Exception", e);
		}
		return versionName;
	}
}
